<script setup>
import router from "@/router/index.js";
import { showToast } from 'vant';
import { toRefs } from 'vue'
import { formatDateTime, formatPrice } from "@/utils/index.js";
import useCountdown from "@/hooks/useCountdown.js";
import {cancelOrder, deleteOrder, getReorder, confirmReceiptOfGoods} from "@/api/order.js";
import { useI18n} from 'vue-i18n';
const { t } = useI18n();
import useSettingStore from '@/store/modules/setting'
const currency = ref(useSettingStore().global.currencySymbol || '')

const props = defineProps({
  item: Object
})
const STATUS_TEXT = {
  '-2': t('order.refundSuccessful'),
  '-1': t('order.cancelled'),
  '0': t('order.due'),
  '1': t('order.goodsWaitingToBeSent'),
  '2': t('order.waitToBeReceived'),
  '3': t('order.completed')
};
const { item } = toRefs(props)
const statusText = STATUS_TEXT[item.value.status] || '' // 订单状态
const { remainingTime } = useCountdown(item.value.time); // 订单倒计时

function goToOrderDetails(id) {
  router.push({path: '/order-detail', query: {id: id}});
}
function goToOrderComment(id) {
  router.push({path: '/order-comment', query: {id: id, form: 'center'}});
}
// 删除当前地址
const delLoading = ref(false)
const delShow = ref(false)
function delOrder() {
  delLoading.value = true
  deleteOrder(item.value.id).then(() => {
    showToast(t('order.successfullyDeleted'))
    delShow.value = false
    delLoading.value = false
    emit('rest')
  }).catch(() => {
    showToast(t('order.deletionFailure'))
    delLoading.value = false
  })
}

// 去付款
function goToPay(id) {
  router.push({path: '/order-detail', query: {id: id, pay: true}});
}

// 取消订单
const cancelShow = ref(false)
const cancelLoading = ref(false)
function clickCancelOrder() {
  cancelLoading.value = true
  cancelOrder(item.value.id).then(() => {
    showToast(t('order.cancelSuccessfully'))
    cancelLoading.value = false
    emit('rest')
  }).catch(() => {
    showToast(t('order.cancellationFailure'))
    cancelLoading.value = false
  })
}

// 获取再次购买信息
const loadingBtn = ref(false)
async function getRePurchaseInfo() {
  loadingBtn.value = true
  try {
    let res = await getReorder(item.value.id);
    let cartIdsString = res.data.cartId.join(","); // 转换为字符串
    loadingBtn.value = false
    router.push({path:'/shopping', query: {
        cartIds: cartIdsString
      }})
  } catch (err) {}
}

// 确认收货
function confirmGoods(id) {
  loadingBtn.value = true
  confirmReceiptOfGoods(id).then(res => {
    showToast(t('order.confirmSuccess'))
    loadingBtn.value = false
    emit('rest')
  }).catch(() => {
    showToast(t('order.failedToConfirm'))
    loadingBtn.value = false
  })
}
// 申请售后
function applyForAfterSales() {
  router.push({path:'/applyAfterSales', query: {
      id: item.value.id
    }})
}
const emit = defineEmits(['rest'])
</script>

<template>
  <div class="order-item">
    <div class="item-top">
      <div class="order-time">
        <div class="order-id">{{t('order.orderNumber')}}：{{item.orderCode}}</div>
        <div class="order-state">{{statusText}}</div>
      </div>
    </div>
    <div class="order-info">
      <div class="product-list">
        <div class="product-item" v-for="product of item.details" :key="item.id">
          <div class="product-img">
            <img :src="product.image" class="pic-img default-img">
            <div class="product-info">
              <div class="product-tit-sku">
                <div class="product-tit">{{product.productName}}</div>
                <div class="product-sku"><span>{{t('order.sku')}}：</span>{{product.sku}}</div>
              </div>
              <div class="priceq-quantity">
                <div class="product-amount">{{currency}}{{formatPrice(product.price)}}</div>
                <div class="product-number">x{{product.num}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="order-detail">
        <div class="order-amount">
          <span class="product-num">{{t('order.total')}}{{item.totalNum}}{{t('order.goodNum')}}</span>
          <span class="product-totalPrice">{{t('order.totalNum')}}：{{currency}}{{formatPrice(item.payPrice)}}</span>
        </div>
        <div class="order-btn">
<!--          评价订单-->
          <div class="white-btn btn" v-if="item.canComment" @click="goToOrderComment(item.id)">{{t('order.comment')}}</div>
<!--          删除订单-->
          <div class="white-btn btn" v-if="item.status === 3 || item.status === -1" @click="delShow = true">{{t('order.deleteAnOrder')}}</div>
<!--          取消订单-->
          <div class="white-btn btn" v-if="item.status === 0" @click="cancelShow = true">{{t('order.cancelAnOrder')}}</div>
<!--          申请售后-->
          <div class="white-btn btn" v-if="item.status === 1 || item.status === 2" @click="applyForAfterSales">{{t('order.applySalesService')}}</div>
<!--          确认收货-->
          <div class="black-btn btn" v-if="item.status === 2" @click="confirmGoods(item.id)">{{t('order.confirmGoods')}}</div>
<!--          继续付款-->
          <div class="black-btn btn" v-if="item.status === 0" @click="goToPay(item.id)">{{t('order.payment')}}</div>
<!--          再次购买-->
          <div class="black-btn btn" v-if="item.status === 3 || item.status === -1" @click="getRePurchaseInfo">{{t('order.repurchase')}}</div>
<!--          查看详情-->
          <div class="black-btn btn" @click="goToOrderDetails(item.id)">{{t('order.orderDetails')}}</div>
        </div>
      </div>
    </div>
<!--    删除订单弹窗-->
    <van-popup v-model:show="delShow" :style="{ padding: '24px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('order.whetherToDelete')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="delShow = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="delLoading" class="s-btn" @click="delOrder">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
<!--    取消订单弹窗-->
    <van-popup v-model:show="cancelShow" :style="{ padding: '24px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('order.whetherToCancelOrder')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="cancelShow = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="cancelLoading" class="s-btn" @click="clickCancelOrder">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
.order-item {
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #8C8C8C;
  .item-top {
    height: 52px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #8C8C8C;
    font-size: 12px;
    .order-time {
      display: flex;
      justify-content: space-between;
      flex: 1;
      .order-id {
        flex: 1;
      }
    }
    .order-del {
      width: 275px;
      text-align: right;
      cursor: pointer;
      font-size: 12px;
      span {
        margin-left: 3px;
      }
    }
  }
  .order-info {
    .product-list {
      flex: 1;
      .product-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #E5E5E5;
        .product-amount {
          font-weight: 600;
        }
        .product-status {
          color: #262626;
          font-weight: 400;
          padding-right: 80px;
          .product-status-text {
            text-align: right;
          }
          .product-btn {
            cursor: pointer;
            margin-top: 5px;
            font-weight: 600;
            text-align: right;
          }
        }
        .product-img {
          display: flex;
          width: 520px;
          img {
            width: 98px;
            height: 110px;
            margin-right: 12px;
          }
          .product-info {
            color: #262626;
            font-size: 14px;
            display: flex;
            flex-flow: column;
            justify-content: space-between;
            flex: 1;
            .product-tit {
              font-weight: 600;
              margin-bottom: 15px;
            }
            .priceq-quantity {
              display: flex;
              justify-content: space-between;
              align-items: center;
            }
            .product-sku {
              font-size: 12px;
              font-weight: 400;
              span {
                color: #8C8C8C;
              }
            }
            .product-number {
              color: #666666;
            }
          }
        }
        .product-info-right {
          display: flex;
          justify-content: space-between;
          align-items: center;
          flex: 1;
        }
      }
      .product-item:last-child {
        border-bottom: none;
      }
    }
    .order-detail {
      width: 100%;
      box-sizing: border-box;
      font-weight: 600;
      color: #262626;
      .order-amount {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 400;
        span {
          font-size: 12px;
          color: #262626;
        }
        .product-totalPrice {
          font-weight: 500;
        }
        .product-num {
          color: #8C8C8C;
        }
      }
      .order-btn {
        cursor: pointer;
        text-align: right;
        margin-top: 15px;
        white-space: nowrap;
        overflow: scroll;
        .btn {
          display: inline-block;
          font-size: 12px;
          height: 32px;
          line-height: 32px;
          padding: 0 7px;
          border: 1px solid #262626;
          border-radius: 2px;
          text-align: center;
          min-width: 76px;
          font-weight: 400;
          margin-left: 10px;
          &:first-child {
            margin-left: 0;
          }
        }
        .black-btn {
          background: #262626;
          color: #FFFFFF;
        }
      }
    }
  }
}
.popup-box {
  width: 100%;
  h3 {
    font-weight: 500;
    font-size: 16px;
    color: #262626;
    text-align: center;
  }
  .btn-box {
    margin-top: 20px;
    display: flex;
    button {
      margin:5px;
      height: 44px;
    }
  }
}
</style>
